package com.xiaoyu.web.sentinel;

import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 将流控规则写入nacos当中，使流控规则实现持久化
 */
@Slf4j
public class NacosFlowRuleWritableDataSource implements WritableDataSource<List<FlowRule>> {

    private final Lock lock = new ReentrantLock(true);
    private ConfigService service;
    private String dataID;
    private String groupID;

    public NacosFlowRuleWritableDataSource(ConfigService service, String dataID, String groupID) {
        this.service = service;
        this.dataID = dataID;
        this.groupID = groupID;
    }

    public void write(List<FlowRule> value) throws Exception {
        //加锁保证线程安全
        lock.lock();
        try {
            log.info("收到sentinel-dashboard控制台推送规则:{}", value);
            //alibaba-fastjson
            String flowJson = JSON.toJSONString(value);
            //推送流控规则到nacos配重中dataId指定的文件flow-rule.json中
            this.service.publishConfig(this.dataID, this.groupID, flowJson, ConfigType.JSON.getType());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void close() throws Exception {

    }

}
